package com.own.component.common.util.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.WritableTypeId;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;

import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * CustomZonedDateTimeSerializer
 *
 * @author chenxueli
 * @date 2024-02-18 10:35:00
 */
public class CustomZonedDateTimeSerializer extends JsonSerializer<ZonedDateTime> {

    private final DateTimeFormatter formatter;

    public CustomZonedDateTimeSerializer(DateTimeFormatter formatter) {
        if (formatter == null) {
            throw new IllegalArgumentException("formatter is null");
        }
        this.formatter = formatter;
    }

    @Override
    public void serialize(ZonedDateTime value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (value == null) {
            jsonGenerator.writeString("");
            return;
        }
        jsonGenerator.writeString(value.format(formatter));
    }

    @Override
    public void serializeWithType(ZonedDateTime value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
        WritableTypeId typeIdDef = typeSer.writeTypePrefix(gen, typeSer.typeId(value, JsonToken.VALUE_STRING));
        serialize(value, gen, serializers);
        typeSer.writeTypeSuffix(gen, typeIdDef);
    }

}
